<style>
.change_pwd .ivu-form-item-error-tip {
    top: 3px;
    left: 103%;
    width: 100%;
}
.head-icon{
    line-height: 58px;
    font-size: 16px;
    color: #ef8411;
    float: left;
    margin-right: 20px;
}
.iconclass{
    display: inline-block;
    width: 58px;
    background: #fff;
    border: 1px dashed #dddee1;
    border-radius: 4px;
    text-align: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color .2s ease;
    height:58px;
    line-height: 58px;
}
.cropper-wrapper {
    margin-top: 10px;
	height: 400px;
}
.cropper-box{
    height: 300px;
}
.btn {
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    background: #fff;
    border: 1px solid #c0ccda;
    color: #1f2d3d;
    text-align: center;
    box-sizing: border-box;
    outline: none;
    margin:20px 10px 0px 0px;
    padding: 9px 15px;
    font-size: 14px;
    border-radius: 4px;
    color: #fff;
    background-color: #50bfff;
    border-color: #50bfff;
    transition: all .2s ease;
    text-decoration: none;
    user-select: none;
}
</style>

<template>
    <div class="change_pwd">
        <product-title></product-title>
        <Row>
            <Col span='8' offset='1'>
            <Form ref="formValidate" :model="formValidate"  :label-width="100">
 
                <Form-item label="头像：">
                    <div>
                        <label for="uploadImg" class='uplaodImg'>
                            <div v-if="get_avatar">
                                <img :src="get_avatar" alt="" width="100" height="100" @click="openModal">
                            </div>
                            <Icon type="image" v-if="!get_avatar" size=20 color="#656464"></Icon>
                        </label>
                        <!-- <input type="file" id="uploadImg" style="position:absolute; clip:rect(0 0 0 0);" accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event)"> -->
                    </div>
                </Form-item>
                <Form-item>
                    <Button type="primary" style="padding:6px 24px;" shape="circle" @click="handleSubmit('formValidate')">提交</Button>
                </Form-item>
            </Form>
            </Col>
        </Row>
        <Modal v-model="modal2" width="1200" ok-text="上传图片" :loading="loading" @on-ok="uploadHeadimg">
            <Row class="cropper-wrapper">
                <Col span="11" class="cropper-box">
                    <vueCropper
                        ref="cropper"
                        :img="headImg.img"
                        :outputSize="headImg.size"
                        :outputType="headImg.outputType"
                        :info="headImg.info"
                        :canScale="headImg.canScale"
                        :autoCrop="headImg.autoCrop"
                        :autoCropWidth="headImg.width"
                        :autoCropHeight="headImg.height"
                        :fixed="headImg.fixed"
                        :fixedNumber="headImg.fixedNumber"
                        @realTime="realTime"
                    ></vueCropper>
                    <label class="btn" for="upload2">打开图片</label>
                    <input type="file" id="upload2" style="position:absolute; clip:rect(0 0 0 0);" accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event)">
                    <!-- <button @click="finish2('base64')" class="btn">裁剪</button> -->
                </Col>
                <Col span="7" offset="1">
                    <!-- <img :src="formItem.headImg.demoimg" /> -->
                    <div class="show-preview" :style="{'width': previews.w + 'px', 'height': previews.h + 'px',  'overflow': 'hidden', 'margin': '5px'}">
                        <div :style="previews.div">
                            <img :src="headImg.img" :style="previews.img">
                        </div>
                    </div>
                </Col>
            </Row>                           
        </Modal> 
    </div>
</template>

<script>
import { mapGetters } from 'vuex';
import productTitle from '../../components/productTitle';
import VueCropper from 'vue-cropper';
//import { accountInfo,changeInfo } from '../../api/me';
import { getStsTokenWrite,getStsTokenRead } from '../../api/common';
import { changeAvatar} from '../../api/yun_user'
export default {
    data() {
        return {
            modal2:false,
            loading: true,
            haveImage: false,
            formValidate: {
                avatar: ''
            },
            headImg: {
                    img: '',
                    info: true,
                    size: 1,
                    canScale:true,
                    outputType: 'jpeg',
                    autoCrop: true,
                    // 只有自动截图开启 宽度高度才生效
                    autoCropWidth: 200,
                    autoCropHeight: 200,
                    // 开启宽度和高度比例
                    fixed: true,
                    fixedNumber: [1, 1],
                    demoimg:'',

            },
            previews: {},
            files:{},
        }
    },
    components: {
        productTitle,
        VueCropper,
    },
    created() {
        //this.getAccountInfo();
        
    },
    mounted () {
        console.log(this.$store.state.user.avator)
    },
    computed: {
      get_avatar(){
          return this.formValidate.avatar ? this.formValidate.avatar : this.$store.state.user.avator
      }  
    },
    methods: {
        openModal(){
            this.modal2 = true  
            if(this.formValidate.avatar){
                this.headImg.img = this.formValidate.avatar
            }else{
                this.headImg.img = ''
            }
        },
        handleSubmit(name) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    this.submit();
                } else {
                    this.$Message.error('验证失败!');
                }
            })
        },
        // getAccountInfo() {
        //     new Promise((resolve, reject) => {
        //         accountInfo().then(response => {
        //             if (response.data.err == 0) {
        //                 this.formValidate = response.data.data
        //                 if(response.data.data.avatar) this.haveImage = true;
        //             } else {
        //                 this.$Message.error(response.data.info);
        //             }
        //             resolve();
        //         }).catch(error => {
        //             reject(error);
        //         });
        //     });
        // },
        handleSubmit() {
            let _params = this.formValidate;
            new Promise((resolve, reject) => {
                changeAvatar(_params).then(response => {
                    if (response.data.err == 0) {
                        this.$Message.success('提交成功!');
                        location.reload();
                    } else {
                        this.$Message.error(response.data.info);
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },
        handleReset(name) {
            this.$refs[name].resetFields();
        },
        // uploadImg(e) {
        //     let file = e.target.files[0]
        //     if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
        //         alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
        //         return false
        //     }
        //     let reader = new FileReader()
        //     reader.onload = (e) => {
        //         this.formValidate.avatar = e.target.result;
        //         this.haveImage = true;
        //     }
        //     reader.readAsDataURL(file)
        // },
        uploadImg (e) {
            //上传图片
            // this.option.img        
            this.files={};
            var file = e.target.files[0];
            this.files = file;
            if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
                alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
                return false
            }
            var reader = new FileReader()
            reader.onload = (e) => {
                this.headImg.img = e.target.result
            }
            reader.readAsDataURL(file);
        },
        // 实时预览函数
        realTime (data) {
            this.previews = data
        },
        toBlob(urlData,fileType){
            var bytes=window.atob(urlData),
                n=bytes.length,
                u8arr=new Uint8Array(n);
            while(n--){
                u8arr[n]=bytes.charCodeAt(n);
            }
            return new Blob([u8arr],{type:fileType});
        },
        uploadHeadimg () {
            this.$refs.cropper.getCropData((data) => {               
                    //this.customer.avator = data
                    //this.formItem.logo = data
                getStsTokenWrite().then((res)=>{
                    if(res.data.err==0){
                        var sts = res.data.data.Credentials;
                        var client = new OSS.Wrapper({
                            region:'oss-cn-hangzhou',
                            accessKeyId: sts.AccessKeyId,
                            accessKeySecret: sts.AccessKeySecret,
                            stsToken: sts.SecurityToken,
                            bucket: 'kuaibao-imgs',
                            secure: true,
                        });
                        var base64 = data.split(',')[1];
                        var fileType = data.split(';')[0].split(':')[1];
                                
                        // base64转blob
                        var blob = this.toBlob(base64,fileType);
                        // blob转arrayBuffer
                        var reader = new FileReader();
                        reader.readAsArrayBuffer(blob);
                        let files = this.files;
                        let size=files.size;
                        let _this = this
                        reader.onload = function (event) {
                            var buffer = new OSS.Buffer(event.target.result);
                            //这里用 multipartUpload  上传会报错，所以更改为 put
                            client.put(files.name, buffer).then((results) => {
                                console.log(results)
                                if(results.url){
                                        _this.$set(_this.formValidate,"avatar",results.url)
                                }else{
                                    _this.$Message.error('上传出错');
                                }
                            })
                        }                  
                    }
                })                                               
            })
            
            this.modal2 = false;
            
        },
    }
};
</script>
